<template>
 <div style="min-height: calc(100vh - 84px);height: 100%;">
  <div >
    <el-row >
      <el-col :xs="24" :sm="24" :lg="6" >
        <div class="layout-all">
          <div class="form-row">
            <div class="title_line"></div>
            <div class="title_text">模块</div>
            <div class="title_text1">拖动到页面</div>
          </div>
          <draggable v-model="del_drag_list" @remove="addHandle" :options="dragOptions" filter=".unmover" :move="onMove" >
              <transition-group tag="div" id="doing1" class="item-ul flex" style="justify-content: flex-start;">
       
            <div class="mokuai" v-for="(item,index) in model_list" :key="index" >
              <template v-if="item.title!=''">
              <i :class="item.img"/>
              {{item.title}}
              </template>
            </div>
       
              </transition-group>
          </draggable>
          <div class="layout-content">
            <control :config="config" @onSearch="onSearchClick"/>
    <div class="layout-header" style="float:left">
        <el-button type="primary" style="margin-left:0px" @click="onAdd">添加</el-button>
    </div>
      <el-table
        :data="tableData"
        stripe
        align="center"
        highlight-current-row
      ><el-table-column align="center" prop="id" label="序号" width="70" :fixed="isMobile()?'left':undefined"/>
        <el-table-column align="center" prop="title" label="名称" />
        <el-table-column align="center" prop="status" label="是否首页" width="100" >
          <template slot-scope="scope">
            <el-button
              :type="scope.row.is_home === 1 ? 'primary' : 'success'"
              size="mini"
              @click="onUpdate(scope.row)"
            >{{ scope.row.is_home === 1 ? "是" : "否" }}</el-button>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="telephone"
          width="160"
          label="操作"
        >
          <template slot-scope="scope">
              <el-button size="small" :type="scope.row.id==id?'warning':'primary'" :icon="scope.row.id==id?'el-icon-mouse':'el-icon-edit'" @click="onEdit(scope.row)"/>
            <el-button
              size="small"
              type="danger"
              icon="el-icon-delete"
              @click="onDel(scope.row.id)"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>
      <el-pagination
        :current-page="current_page"
        :page-size="per_page"
        layout="total, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="8" >
        <div class="layout-all">
          <div class="form-row">
            <div class="title_line"></div>
            <div class="title_text">页面</div>
            <div class="title_text1">拖动到左边删除</div>
          </div>
          
          <div class="conter" style="margin-top: 10px;width:371px;border:1px solid #cdcdcd ;padding:5px;border-radius:10px">
          <draggable v-model="page_list" @remove="removeHandle" :options="dragOptions" filter=".unmover" :move="onMove" >
              <transition-group tag="div" id="doing" class="item-ul" :style="'height:600px;background:'+page_list[0].data.end_bg">
                  <div v-for="(item,index) in page_list" :key="index" style="position:relative;z-index: 1;" :class="item.type=='head'?'unmover':''">
                    <div class="zhezhao" :style="select_index==index?'border: 2px #ff0000 dashed;box-sizing:border-box;z-index: 10; ':''" @click="click_select(index)"></div>
                    <component  :is="'item-'+item.type" :data="item.data"  @click.native="click_select(index)"
                    :style="'margin-left:'+item.data.margin_w+'px;margin-right:'+item.data.margin_w+'px;margin-top:'+item.data.margin_top+'px;padding:'+
                    item.data.padding_h+'px '+item.data.padding_w+'px;'+(item.data.is_background==0?('background:'+item.data.background+';'):'')+'border-radius:'+item.data.radius+'px;'+
                    (item.data.is_border?('box-shadow:'+ item.data.shadow_color+' 0px 0px '+ item.data.shadow_size+
                    'px;border:'+item.data.border_size+'px solid '+item.data.border_color):'')"></component>
                  </div>
              </transition-group>
              
          </draggable>
          <div style="position: relative;" v-if="formArray!=undefined&&formArray.is_home==1">
               <div class="zhezhao bottom-border" :style="select_index==-1?'border: 2px #ff0000 dashed;box-sizing:border-box;z-index: 10; ':''" @click="click_select(-1)"></div>
              <item-bottomtab :data="bottom.data"
              :style="'margin-left:'+bottom.data.margin_w+'px;margin-right:'+bottom.data.margin_w+'px;margin-top:'+bottom.data.margin_top+'px;padding:'+
                    bottom.data.padding_h+'px '+bottom.data.padding_w+'px;'+(bottom.data.is_background==0?('background:'+bottom.data.background+';'):'')+'border-radius:'+bottom.data.radius+'px;'+
                    (bottom.data.is_border?('box-shadow:'+ bottom.data.shadow_color+' 0px 0px '+ bottom.data.shadow_size+
                    'px;border-top:'+bottom.data.border_size+'px solid '+bottom.data.border_color):'')" 
               @click.native="click_select(-1)"/>
              </div>
          </div>
          
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="10" >
        <div class="layout-all" >
          <div class="form-row">
            <div class="title_line"></div>
            <div class="title_text">名称</div>
            <template v-if="formArray!=undefined">
            <el-input  v-model="formArray.title" style="margin-left:10px;width:200px" placeholder="请输入名称" />
            <el-tag type="primary" style="margin-left:10px" v-if="form!=undefined">{{model_list[form.type]==undefined?model_hide_list[form.type].title:model_list[form.type].title}}</el-tag>
            <el-button type="success" size="small" style="margin-left:10px" @click="onSave">保存<i class="el-icon-upload el-icon--right"></i></el-button>
            <el-button type="danger" size="small" style="margin-left:10px" @click="onReload">重置<i class="el-icon-refresh-left"></i></el-button>
            </template>
          </div>
          <el-form v-if="form!=undefined" class="layout-all" :model="form" label-width="100px" :label-position="isMobile()?'top':'left'" style="overflow-y:auto;height:660px;">
            <div v-for="(value,j) in form.type=='head'?[model_hide_list[form.type].data]:[appearance,model_list[form.type]==undefined?model_hide_list[form.type].data:model_list[form.type].data]" :key="j">
              <el-card class="box-card" style="padding-bottom: 50px;">
              <div slot="header" class="clearfix">
                <span>{{j==0?'基础设置':'扩展设置'}}</span>
              </div>
              <div v-for="(item,index) in value" :key="index" :style="'float:'+(item.type=='slider'?'none':'left')+';clear:'+(item.nofloat==undefined?'':'left')+';margin-left:10px;'+
              (item.bottom_border==undefined?'':'border-'+(item.bottom_border==0?'top':'bottom')+': 1px solid rgb(224, 224, 224);')" >
               <!-- 字体大小 -->
               <el-form-item :label="item.title+':'" label-width="130px" prop="title" v-if="item.type=='slider'&&(item.condition==undefined||form.data[item.condition[0]]==item.condition[1])">
               <el-tooltip class="item" :disabled="item.tip==undefined" effect="dark" :content="item.tip" placement="top-start">
               <el-slider :min="item.min" :max="item.max" input-size="mini" v-model="form.data[item.field]" show-input />
               </el-tooltip>
               </el-form-item>
               
               <div class="flex" v-else-if="item.condition==undefined||form.data[item.condition[0]]==item.condition[1]" >
                 <div style="line-height:40px;margin-right:5px">
                   {{item.title+':'}}
                 </div>
                 <div>
                   <el-tooltip class="item" :disabled="item.tip==undefined" effect="dark" :content="item.tip" placement="top-start">
                   <el-input v-if="item.type=='input'" v-model="form.data[item.field]" :placeholder="item.title" />
                   <!-- 选择颜色 -->
                  <el-color-picker :predefine="predefineColors" show-alpha v-if="item.type=='color'" v-model="form.data[item.field]"></el-color-picker>
                  <template v-if="item.type=='colorArr'">
                  <el-color-picker :predefine="predefineColors" show-alpha  v-model="form.data[item.field][i]" v-for="(color,i) in form.data[item.field]" :key="i"></el-color-picker>
                  </template>
                  <!-- 选择框 -->
                  <el-radio-group v-if="item.type=='select'" v-model="form.data[item.field]" type="success" size="small" round @change="onChangeRadio($event)">
                    <el-radio-button v-for="(op,i) in item.list" :key="i" :label="i">{{op}}</el-radio-button>
                  </el-radio-group>
                  <!-- 多选框 -->
                  <el-checkbox-group v-if="item.type=='checkbox'" v-model="form.data[item.field]" type="success" size="small" round >
                    <el-checkbox-button v-for="(op,i) in item.list" :key="i" :label="i">{{op}}</el-checkbox-button>
                  </el-checkbox-group>
                  <!-- 开关 -->
                  
                  <el-switch v-if="item.type=='switch'" v-model="form.data[item.field]" active-color="#13ce66" inactive-color="#ff4949"  style="margin-top:10px"></el-switch>
                  <!-- 图片 -->
                  <upload-pic v-if="item.type=='thumb'" 
                  :thumb="form.data[item.field]" @update:thumb="onThumb($event,item.field)" :width="item.width" 
                  :height="item.height_field!=undefined?(form.data[item.height_field]/(item.height_field_column!=undefined?3.55/(form.data[item.height_field_column]+1):3.55)).toFixed(0):item.height" cate_id="2"/>
                  <!-- 轮播 -->
                  <upload-banners-url v-if="item.type=='banner'" :is_url="item.is_url!=undefined?1:0" :list="form.data[item.field]" :width="item.width" :horn="item.horn==undefined?0:1" 
                  :no_thumb="item.no_thumb!=undefined?1:0" :height="item.height_field!=undefined?(form.data[item.height_field]/(item.height_field_column!=undefined?3.55/(form.data[item.height_field_column]+1):3.55)).toFixed(0):item.height" cate_id="2"/>
                  <!-- 秒杀 -->
                  <setting-offer v-if="item.type=='offer'" :list="form.data[item.field]" />
                  <!-- 导航 -->
                  <setting-bottom :options="options" v-if="item.type=='bottom'" :list="form.data[item.field]" />
                  <!-- 字体图标 -->
                  <icon-browser :icon="form.data[item.field]" @onChange="selectIcon($event,item.field)" v-if="item.type=='classFont'" />
                  <!-- 选择任意一级选项 -->
                  <el-cascader v-if="goodsCate!=undefined&&item.type=='goods_cate'" style="width:240px" v-model="form.data[item.field]" :options="goodsCate" :props="cate_expand" clearable></el-cascader>
                  <!-- 选择商品 -->
                  <el-select v-if="goods_list!=undefined&&item.type=='goods_list'" style="width:600px" v-model="form.data[item.field]" clearable filterable multiple placeholder="请选择">
                    <el-option v-for="item in goods_list" :key="item.id" :label="item.title" :value="item.id" />
                  </el-select>
                  
                  </el-tooltip>
               </div>
               
               </div>
            </div>

              </el-card>
            </div>
          </el-form>

        </div>
      </el-col>
    </el-row>
  </div>
  </div>
</template>

<script>
import components from './model'
import UploadBannersUrl from "@/components/UploadPic/UploadBannersUrl";
import iconBrowser from '@/components/tool/iconBrowser'
import draggable from 'vuedraggable'
import control from '../../components/control/control'
const modelArray = require('./model/modelArray.js')
export default {
  name:'index_ui_diy',
  components: { 
    draggable:draggable,
    control:control,
    UploadBannersUrl:UploadBannersUrl,
    iconBrowser:iconBrowser,
    ItemHead:components.ItemHead,
    ItemSearch:components.ItemSearch,
    ItemBackground:components.ItemBackground,
    ItemBanner:components.ItemBanner,
    ItemNav:components.ItemNav,
    ItemAdvertising:components.ItemAdvertising,
    ItemNotice:components.ItemNotice,
    ItemOffer:components.ItemOffer,
    ItemActivity:components.ItemActivity,
    ItemActivity:components.ItemActivity,
    ItemCommodities:components.ItemCommodities,
    SettingOffer:components.SettingOffer,
    SettingBottom:components.SettingBottom,
    ItemBottomtab:components.ItemBottomtab,
    ItemMaintitle:components.ItemMaintitle,
  },
  data() {
    return {
      cate_expand:{
        value: 'id',
        label: 'title',
        children: 'child',
        checkStrictly: true,
      },
      id:0,
      config: [
        { type: 'text', placeholder: '请输入标题', field: 'title', val: '' }
      ],
      searchWhere: {
        title: ''
      },
      tableData: [],
      formArray: [],
      
      current_page: 1,
      per_page: 14,
      total: 0,
      bottomJson:'',
      model_list: [],
      options: [],
      goods_list: undefined,
      goodsCate: undefined,
      del_list:[],
      del_drag_list:[],
      predefineColors:['rgba(0, 0, 0, 0)','#ffffff','#f0f0f0','#ff4500','#ff8c00','#ffd700','#90ee90','#00ced1','#1e90ff','#c71585',],
      select_index:-2,
      form:undefined,
      dragOptions:{
          animation: 120,
          scroll: true,
          group: 'sortlist',
          ghostClass: 'ghost-style'
      },
      bottom:{type:'bottom',data:{
        title_color:'#999999',
        check_color:'#ff0000',
        title_size:12,
        icon_size:30,
        bottom_padding_h:7,
        hight:55,
        title_top:3,
        list:[
            {big:false,title:'首页',icon:'iconfont icon-icon_huabanfuben',path:'index',is_thumb:0},
            {big:false,title:'分类',icon:'iconfont icon-integral',path:'classfiy',is_thumb:0},
            {big:false,title:'购物车',icon:'iconfont icon-cart-Empty',path:'shopcar',is_thumb:0},
            {big:false,title:'我',icon:'iconfont icon-account',path:'member',is_thumb:0},
          ]
        },
      },
      page_list:[
        {type:'head',unmover:1,data:{
          bg:'#039dff',//头部背景颜色
          title:'首页',//标题
          title_color:'#fff',//标题文字颜色
          title_size:16,//标题文字大小

          banner:[],//判断是否用图片
          thumb:'',
          is_thumb:0,
          background_size:125,
          background:['#014aff','#039dff'],//渐变背景颜色
          end_bg:'#f0f0f0',//渐变背景颜色
        },},
      ],
      appearance:[],
        //不出现在左部的属性
      model_hide_list:{},
    }
  },
  activated(){
    if(this.$getUpdate()){
      this.onSearch()
    }
  },
  created() {

    this.model_list=modelArray.model_list
    this.model_hide_list=modelArray.model_hide_list
    this.appearance=modelArray.appearance
    this.onSearch()
  },
  methods: {
    selectIcon(event,field) {
      this.form.data[field] = event
    },
    onThumb(url,field){
      this.$set(this.form.data,field,url)
    },
    //move回调方法
    onMove(e,originalEvent){
      if(this.page_list.length==1)return true
      //不允许停靠
      if (e.relatedContext.index <1) return false;
      return true;
    },  
    click_select(index){
      this.select_index=index
      if(index<0){
        this.form=this.bottom
      }else{
        this.form=this.page_list[index]
      }
      if(this.form.type=="commodities"){
        if(this.form.data.sources==4){
          this.getGoodsCate()
        }else if(this.form.data.sources==5){
          this.getGoodsList()
        }
      }
    },
    removeHandle(event){
        this.$message.success(`移动到回收站`);
        this.del_list.push(this.del_drag_list[0])
        this.del_drag_list=[]
        this.click_select(event.oldDraggableIndex-1)
    },
    addHandle(event){
      let n=0;
      for(let i in this.model_list){
        if(n==event.oldDraggableIndex){
          console.log(this.model_list[i].title)
          for(let j in this.del_list){
            if(i==this.del_list[j].type){
              this.page_list.splice(event.newDraggableIndex,0,this.del_list[j])
              this.$delete(this.del_list,j)
              // console.log(this.del_list)
              // console.log(this.page_list)
              this.$message.success(`恢复了一个 ${this.model_list[i].title} `);
              this.click_select(event.newDraggableIndex)
              return
            }
          }

          this.page_list.splice(event.newDraggableIndex,0,JSON.parse(JSON.stringify(this.model_list[i].def)))
          this.$message.success(`增加了一个 ${this.model_list[i].title} `);
          this.click_select(event.newDraggableIndex)
          return
        }
        n++
      }
    },
    handleSizeChange(val) {
      this.onSearch()
    },
    handleCurrentChange(val) {
      this.current_page = val
      this.onSearch()
    },
    onSearchClick(map){
      this.current_page = 1
      this.searchWhere=map
      this.onSearch()
    },
    onSearch() {
      const form = {}
      form.page = this.current_page
      form.map = this.searchWhere
      this.get('/admin/DiyPages/index', form, 'POST').then(e => {
        this.tableData = e.list.data
        this.per_page = e.list.per_page
        this.total = e.list.total
        this.current_page = e.list.current_page
        this.bottomJson=e.bottom
        if(e.bottom&&e.bottom!=''){
          this.bottom = JSON.parse(e.bottom)
          if(this.select_index<0){
            this.form=this.bottom
          }
        }
        if(this.page_list.length<=1&&e.list.data.length>0){
          this.goto(e.list.data[0])
        }
      })
    },
    onReload(){
      this.$confirm('您确认要放弃本次更改恢复为上次保存的状态吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if(this.formArray.content&&this.formArray.content!=''){
            this.page_list=JSON.parse(this.formArray.content)
          }else{
            this.page_list=[JSON.parse(JSON.stringify(this.model_hide_list.head.def))]
          }
        }).catch(() => {
          
        });
    },
    // 添加
    onAdd() {
      this.check_save(()=>{
        this.$prompt('请输入名称', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /.+/,
          inputErrorMessage: '请输入名称'
        }).then(({ value }) => {
          this.id=0
          this.select_index=-2
          this.form=undefined
          this.formArray={content:'',is_home:0,title:value}
          this.page_list=[JSON.parse(JSON.stringify(this.model_hide_list.head.def))]
        })
      })
    },
    //单选框选中事件
    onChangeRadio(e){
      console.log(e)
      if(this.form.type=="commodities"){
        if(e==4){
          this.getGoodsCate()
        }else if(e==5){
          this.getGoodsList()
        }
        
      }
    },
    getGoodsCate(){
      if(this.goodsCate==undefined){
        this.get("admin/GoodsCate/info?id=0", "post").then((e) => {
          this.goodsCate = e.parent;
        });
      }
    },
    getGoodsList(){
      if(this.goods_list==undefined){
        this.get("admin/Goods/get_list", "post").then((e) => {
          this.goods_list = e.goods_list;
        });
      }
    },
    check_save(fun){
      if(this.formArray!=undefined&&(this.formArray.content!=''||this.page_list.length>1)&&JSON.stringify(this.page_list)!=this.formArray.content){
        this.$confirm('当前编辑的内容尚未保存,若不用保存请选放弃修改', '提示', {
          confirmButtonText: '放弃修改',
          cancelButtonText: '返回保存',
          type: 'warning'
        }).then(() => {
          fun()
        }).catch(() => {
          
        });
      }else{
        fun()
      }
    },
    goto(row){
      this.id=row.id
      this.select_index=-2
      this.form=undefined
      this.formArray=row
      if(row.content&&row.content!=''){
        this.page_list=JSON.parse(row.content)
      }else{
        this.page_list=[JSON.parse(JSON.stringify(this.model_hide_list.head.def))]
      }
    },
    // 编辑
    onEdit(row) {
      this.check_save(()=>{
        this.goto(row)
      })
    },
    onSave() {
      const form = {}
      let content=JSON.stringify(this.page_list)
      if(this.formArray.is_home==1){
        let saveBottom=JSON.stringify(this.bottom)
        if(this.bottomJson!=saveBottom){
          this.bottomJson=saveBottom
          form.bottomJson=saveBottom
        }
      }
      if(this.formArray.content!=content){
        for(let i=0 ;i<this.page_list.length-1;i++){
          let v=this.page_list[i]
          if(v.type=='commodities'&&v.data.sources_num==0){
            this.$msg_ok('error','设置显示数量为0即为有分页,有分页的组件只能在页尾显示')
            this.click_select(i)
            return
          }
        }
        this.formArray.content=content
        form.content=content
        form.title=this.formArray.title
      }
      if(JSON.stringify(form) == "{}"){
        this.$msg_ok('success','无需保存')
        return
      }
      if(this.formArray.id)
      form.id=this.formArray.id
      this.get('/admin/DiyPages/save', form, 'POST').then(e => {
        this.$msg_ok('success','保存成功')
        this.onSearch()
      })
    },
    onUpdate(row) {
      if(row.is_home==1)return
      this.$confirm('确定要将 '+row.title+' 设为首页吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        this.get('/admin/DiyPages/set_home?id=' + row.id, {}, 'POST').then(e => {
          this.onSearch()
          this.$message({
            type: 'success',
            message: '设置成功!'
          })
        })
      })
    },
    // 删除
    onDel(id) {
      this.$confirm('是否删除该记录', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.get('/admin/DiyPages/del?id=' + id, this.form, 'POST').then(e => {
          this.onSearch()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>

.layout-all {
  margin-top: 20px;
  margin-left: 10px;
  position: relative;
  
}
.layout-content {
  margin-top: 20px;
}
.title_line {
  height: 20px;
  width: 5px;
  background-color: #744cf9;
}
.title_text {
  margin-left: 10px;
  font-size: 18px;
  color: #333333;
}

.title_text1 {
  margin-left: 20px;
  font-size: 14px;
  color: #999999;
}
.zhezhao{
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: 0;
}
/* 拖拽 */
    .item-ul{
        /* padding: 0 8px 8px; */

        overflow-y: scroll;
    }
    .item-ul::-webkit-scrollbar{
        width: 0;
    }

        .drag-list {
        border: 1px #e1e4e8 solid;
        padding: 10px;
        margin: 5px 0 10px;
        list-style: none;
        background-color: #fff;
        border-radius: 6px;
        cursor: pointer;
        -webkit-transition: border .3s ease-in;
        transition: border .3s ease-in;
    }
    .drag-list:hover {
        border: 1px solid #20a0ff;
    }
/* 拖拽 */
.mokuai{
  width: 80px;
  height: 80px;
  border: 1px solid #eee;
  text-align: center
}
.flex{
  display: flex;
  flex-wrap: wrap;
}
.mokuai i{
  display: block;
  font-size:25px;
  margin-top: 5px;
  margin-bottom: 2px;
}
.conter{
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}
.bottom-border{
    width: 371px;
    margin-top: -10px;
    margin-left: -5px;
    height: 130%;
}
</style>
